package com.seven.restaurant.util;

import com.seven.restaurant.exception.GlobalException;
import com.seven.restaurant.exception.ValidationException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>数据效验的工具类</p>
 * @author BaiBan
 * @since 2022/6/4
 */
public class ValidationUtil {

    private static final Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    /**
     * 请求参数效验方法
     * @param entity 数据效验的实体对象
     * @throws ValidationException 参数错误类
     */
    public static <Type> void validation(Type entity) throws ValidationException {
        // 效验 获得效验结果
        Set<ConstraintViolation<Type>> validate = validator.validate(entity);
        if(validate.size() != 0) {
            StringBuilder message = new StringBuilder();
            for (ConstraintViolation<Type> violation : validate) {
                message.append(violation.getMessage() + ",");
            }
            throw new ValidationException(message.toString());
        }
    }
}